package com.glodon.paas.document.web.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.glodon.paas.document.api.bean.File;
import com.glodon.paas.document.api.bean.FileQuery;
import com.glodon.paas.document.service.FileService;
import com.glodon.paas.document.service.util.WebService;
import com.glodon.paas.document.web.util.SecurityUtils;
import com.glodon.paas.exception.PrivilegeException;

@Controller
public class SearchController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private FileService fileService;

    @RequestMapping(value = "/search/file", method = RequestMethod.GET, produces = "application/json")
    public ResponseEntity<List<File>> searchFile(FileQuery query) {
        String userId = SecurityUtils.getCurrentUser().getId();
        query.setOwnerId(userId);
        List<File> list = WebService.doSearch(query);
        for (int i = 0; i < list.size(); i++) {
            File file = list.get(i);
            try {
                file = fileService.getFile(userId, file.getId(), true);
                list.set(i, file);
            } catch (PrivilegeException e) {
                logger.warn(e.getMessage(), e);
            } catch (Exception e) {
                logger.warn("failed to convert from search to document file.", e);
            }
        }
        return new ResponseEntity<List<File>>(list, HttpStatus.OK);
    }
}
